package com.longge;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-02-28 22:58
 */
public class BuildTree {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0) return null;
        return build(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
    }

    private TreeNode build(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {

        if (preStart > preEnd) {
            return null;
        }
        int rootVal = preorder[preStart];
        int index = -1;
        for (int i = inStart; i <= inEnd; i++) {
            if (rootVal == inorder[i]) {
                index = i;
            }
        }
        TreeNode treeNode = new TreeNode(rootVal);
        treeNode.left = build(preorder, preStart+1, preStart+index-inStart, inorder,inStart ,index-1 );
        treeNode.right = build(preorder,preStart+index-inStart+1 , preEnd, inorder,index+1 ,inEnd);
        return treeNode;
    }
}
